/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package classes;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.AbstractSet;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Projections;
import pojo.BookHasOrder;
import pojo.Order;

/**
 *
 * @author DELL
 */
public class Buy extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Set<BookHasOrder> cart = (Set) request.getSession(false).getAttribute("cart");
        Set<BookHasOrder> buyed = new HashSet<>();
        pojo.Customer c = (pojo.Customer) request.getSession(false).getAttribute("user");
        String errorMsg = "";
        boolean done = true;
        for (BookHasOrder bho : cart) {
            if (request.getParameterValues(bho.getBook().getTitle()) != null) {
                String num = request.getParameter("quan" + bho.getBook().getTitle());
                int quan = 0;
                try {
                   quan = Integer.parseInt(num);
                } catch (Exception ex) {
                    System.out.println("invalid input ");
                }
                bho.setQuantity(quan);
                buyed.add(bho);
                errorMsg = "<h3>Sorry, There are sum errors:<br/>";
            }
        }
        int sum = 0;
        for (BookHasOrder bho : buyed) {
            if (bho.getBook().getQuantity() < bho.getQuantity()) {
                done = false;
                errorMsg += "Not Enough Quantity for " + bho.getBook().getTitle() + " Book, There's Only " +bho.getBook().getQuantity()+ " Book(s)<br/>";
            }
            sum += bho.getBook().getPrice() * bho.getQuantity();
        }
        if (sum > c.getCredit()) {
            done = false;
            errorMsg += "Not Enough Credit</h3>";
        }
        if (done && sum>0) {
            Session hSession = new Configuration().configure().buildSessionFactory().openSession();
            hSession.beginTransaction();
            pojo.Order cartorder = c.getCartOrder();
            for (BookHasOrder bho : buyed) {
                
                pojo.Book book = bho.getBook();
                book.setQuantity(bho.getBook().getQuantity() - bho.getQuantity());
               // book.getBookHasOrders().remove(bho);
                cartorder.getBookHasOrders().remove(bho);
                hSession.merge(book);
                hSession.delete(bho);
                
            }

            hSession.merge(cartorder);
            c.setCredit(c.getCredit() - sum);
            request.getSession(false).setAttribute("cart", c.getCart());
            pojo.Order order = new Order();
            order.setOrderDate(new Date());
            order.setCustomer(c);
            order.setBookHasOrders(buyed);
            c.getOrders().add(order);
            int id=-1;
            try
            {
              // id = (int) hSession.createSQLQuery("select max(id) from mydb.order").uniqueResult();
              id =  (int) hSession.createCriteria(Order.class).setProjection(Projections.max("id")).uniqueResult();
            }catch(Exception ex){}
            order.setId(1+id );
            hSession.persist(order);
            hSession.merge(c);
            hSession.getTransaction().commit();
            hSession.close();
            errorMsg = "<h3>Congratulations :)</h3>";
        }
        request.getRequestDispatcher("Header.jsp").include(request, response);
        request.getRequestDispatcher("caret.jsp").include(request, response);
        response.getWriter().println(errorMsg);
        request.getRequestDispatcher("Footer.jsp").include(request, response);
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
